/**
 *通用形select
 */
<template>
    <el-select
        v-model="selectVal"
        :multiple="multiple"
        :collapse-tags="collapseTags"
        :collapse-tags-tooltip="collapseTagsTooltip"
        :max-collapse-tags="maxCollapseTags"
        
        :clearable="clearable"
        :placeholder="placeholder"
        :disabled="disabled"
        :size="size"
        :multiple-limit="multipleLimit"
        :filterable="filterable"
        :allow-create="allowCreate"
        :filter-method="filterMethod"
        :remote="remote"
        :remote-method="remoteMethod"
        :remote-show-suffix="remoteShowSuffix"
        :loading="loading"
        :loading-text="loadingText"
        :no-match-text="noMatchText"
        :no-data-text="noDataText"
        :default-first-option="defaultFirstOption"
        @change="selectChange"
    >
        <el-option
            v-for="item in newOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled"
        />
    </el-select>
</template>

<script lang="ts" setup>
    import { ref, reactive, markRaw, onBeforeMount, onMounted, onBeforeUnmount, nextTick, computed, watch  } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { findBySelectNameDefaultApi } from '@/apis'
    import { isPhone } from '@/utils'

    import { useRoute, useRouter } from 'vue-router'
    import { storeToRefs } from 'pinia'
    import { useStore } from '@/store'
    import { ElMessage } from 'element-plus'
    import {
        Lock,
        User,
        Monitor,
        Phone,
        Search,
        RefreshRight,
    } from '@element-plus/icons-vue'

    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const selectVal: Ref<any> = ref('')

    const defaultValue = defineModel<any>({
        required: false,
        default: ''
    })
            
    const { 
            multiple = false, 
            collapseTags = false, 
            collapseTagsTooltip = false, 
            maxCollapseTags = 1, 
            clearable = false, 
            multipleValueIsNumber = false, 
            disabled= false, 
            size= '', 
            multipleLimit = 0, 
            filterable = false, 
            allowCreate = false, 
            filterMethod = () => {}, 
            remote = false, 
            remoteMethod = () => {}, 
            remoteShowSuffix = false, 
            loading = false, 
            loadingText = '加载中', 
            noMatchText = '暂无匹配选项', 
            noDataText = '暂无选项', 
            defaultFirstOption = false, 
            placeholder = '请选择', 
            options = [], 
            dictionary = {},
            defalutOptionsIndex = ''
        } = defineProps<{
        multiple?: boolean, 
        collapseTags?: boolean,  //多选时是否将选中值按文字的形式展示
        collapseTagsTooltip?: boolean, //当鼠标悬停于折叠标签的文本时，是否显示所有选中的标签。 要使用此属性，collapse-tags属性必须设定为 true
        maxCollapseTags?: number, //需要显示的 Tag 的最大数量 只有当 collapse-tags 设置为 true 时才会生效。
        clearable?: boolean, 
        multipleValueIsNumber?: boolean, 
        disabled?: boolean,
        size?: string,
        multipleLimit?: number, //multiple 属性设置为 true 时，代表多选场景下用户最多可以选择的项目数， 为 0 则不限制
        filterable?: boolean, //Select 组件是否可筛选
        allowCreate?: boolean, //是否允许用户创建新条目， 只有当 filterable 设置为 true 时才会生效。
        filterMethod?: Function, //自定义筛选方法
        remote?: boolean, //其中的选项是否从服务器远程加载
        remoteMethod?: Function, //自定义远程搜索方法
        remoteShowSuffix?: boolean, //远程搜索方法显示后缀图标
        loading?: boolean, //是否正在从远程获取数据
        loadingText?: string, //远程搜索方法显示后缀图标
        noMatchText?: string, //搜索条件无匹配时显示的文字，也可以使用 empty 插槽设置，默认是 “No matching data'”
        noDataText?: string, //无选项时显示的文字，也可以使用 empty 插槽设置自定义内容，默认是 “No data”
        defaultFirstOption?: boolean, //是否在输入框按下回车时，选择第一个匹配项。 需配合 filterable 或 remote 使用
        placeholder?: string, 
        options?: any[], 
        dictionary?: any,
        defalutOptionsIndex?: any,
    }>()
    const emits = defineEmits<{
        // (e: 'update:isCollapse', data: boolean): void,
        // tabelSearch: [data: any],
    }>()
    const newOptions: Ref<any[]> = ref([])

    if (dictionary?.name) {
        findBySelectNameDefaultApi({
            name: dictionary?.name
        }).then((res: any) => {
            newOptions.value = res.data
            // 有默认选项
            if ((defalutOptionsIndex || defalutOptionsIndex == 0) && defalutOptionsIndex!= '') {
                console.log(defalutOptionsIndex == '')
                if (multiple) {
                    let arr = []
                    if (defalutOptionsIndex instanceof Array) {
                        defalutOptionsIndex.forEach((item: any) => {
                            arr.push(res.data[item].value)
                        })
                        defaultValue.value = arr
                    } else if (typeof defalutOptionsIndex == 'string') {
                        defalutOptionsIndex.split(',').forEach((item: any) => {
                            arr.push(res.data[item].value)

                        })
                        defaultValue.value = arr.join(',')
                    }
                } else {
                    defaultValue.value = res.data[Number(defalutOptionsIndex)]?.value
                }
                
            }
        })
    }
    
    watch(() => options, (nval: any, oval) => {
        if(options.length > 0) {
            newOptions.value = options
        }
    }, {
        immediate: true,
    })
    watch(defaultValue, (nval: any, oval) => {
        // 判断是不是数组
        if (multiple) {
            if (nval instanceof Array) {
                selectVal.value = nval
            } else if (typeof nval == 'string') {
                if (nval) {
                    if (multipleValueIsNumber) {
                        selectVal.value = nval?.split(',').map((item: any) => {
                            return item = Number(item)
                        })
                    } else {
                        selectVal.value = nval?.split(',')
                    }
                } else {
                    selectVal.value = []
                }
            }
        } else {
            selectVal.value = nval
        }
    }, {
        immediate: true,
    })
    const selectChange = (val) => {
        // console.log(val)
        // console.log(selectVal.value)
        if (multiple) {
            if (defaultValue.value instanceof Array) {
                defaultValue.value = val
            } else {
                defaultValue.value = val.join(',')
            }
        } else {
            defaultValue.value = val
        }
    }
    
</script>

<style lang="scss" scoped>
    .generalTabel {
        width: 100%;
        height: 100%;
        background: #fff;
        box-sizing: border-box;
        padding: 20px;
        text-align: left;
        display: flex;
        flex-direction: column;
    }
</style>